<?php


namespace models\Business\Tbk;

use models\Exception\Business\TbkproductException;
use Yaf\Registry;
use youliPhpLib\Common\RequestHelper;
use models\Business\Tbk\TbkSdk\Tbk;


class TkUrl
{
    const TKURL_APP = 'AvJgsP8b';

    // 拉取淘客订单
    const TKURL_ORDER_LIST_URL = 'http://api.tkurl.top/tbk_order_v2';
    // huangxu4328的session
//    const SESSION = '7000010094978546da8b0cbe5b8d595d03eaa097a69bc1135bc2e77ac008a1901b19fd2375120856';
    // 厦门宥理79712的session
    const SESSION = "70000100d194971b46c820bffa567a213e809eee0f2f1110f001f8a0639cf0a436a676a2208129349928";

    //
    const TKURL_CONVERT_URL = "http://api.tkurl.top/privilege";

    // 解析淘口令
    const TKURL_TPWD_CONVERT_URL = "http://api.tkurl.top/api/alimama/tpwd_convert";

    // pid 厦门宥理79712 mm_1203700167_1756300055_110470150060
    const PID = "mm_1203700167_1756300055_110470150060";

    static public function privilege($item_id = '') {
//        $item_id = '585952528418';
        $url_arr['id'] = $item_id;
        $url_arr['pid'] = self::PID;
        $url_arr['session'] = self::SESSION;
        $url_arr['appkey'] = self::TKURL_APP;

        $url = self::TKURL_CONVERT_URL . '?' . http_build_query($url_arr);

        list($header_size, $resp) = RequestHelper::curlRequest($url, '', 'GET');
        $resp = json_decode($resp, true);

        if (isset($resp['error_response'])) {
            Registry::get('tbk_log')->err('接口查无数据' . json_encode($resp));
            throw new TbkproductException(TbkproductException::TBKPRODUCT_IS_NOT_EXISTS, TbkproductException::TBKPRODUCT_IS_NOT_EXISTS_NO);
        }

        if (isset($resp['tbk_privilege_get_response']['result']['data'])) {
            $product = Tbk::getProductInfo($item_id);

            $product['link'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_click_url']) ?
                $resp['tbk_privilege_get_response']['result']['data']['coupon_click_url'] : '';
            $product['coupon_end_time'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_end_time']) ?
                $resp['tbk_privilege_get_response']['result']['data']['coupon_end_time'] : '0000-00-00 00:00:00';
            $product['coupon_start_time'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_start_time']) ?
                $resp['tbk_privilege_get_response']['result']['data']['coupon_start_time'] : '0000-00-00 00:00:00';
            $product['coupon_explain'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_info']) ?
                $resp['tbk_privilege_get_response']['result']['data']['coupon_info'] : '';
            $product['coupon_num'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_total_count']) ?
                $resp['tbk_privilege_get_response']['result']['data']['coupon_total_count'] : 0;
            $product['coupon_receive'] = isset($resp['tbk_privilege_get_response']['result']['data']['coupon_total_count']) &&
                isset($resp['tbk_privilege_get_response']['result']['data']['coupon_remain_count']) ?
                ($resp['tbk_privilege_get_response']['result']['data']['coupon_total_count'] -
                    $resp['tbk_privilege_get_response']['result']['data']['coupon_remain_count']) : 0;
            $product['rate'] = isset($resp['tbk_privilege_get_response']['result']['data']['max_commission_rate']) ?
                $resp['tbk_privilege_get_response']['result']['data']['max_commission_rate'] : 0.00;
            $product['commission'] = isset($product['rate']) ? ($product['rate'] * $product['price'] / 100) : 0;

            if (preg_match_all('/满(\d+)元减(\d+)元/Usi', $product['coupon_explain'], $arr)) {
                $product['end_price'] = $product['price'] >= $arr[1][0] ? $product['price'] - $arr[2][0] : 0;
                $product['coupon_price'] = $arr[2][0];
            } else {
                $product['end_price'] = $product['price'];
                $product['coupon_price'] = 0;
            }

            return $product;
        }
        else
            throw new TbkproductException(TbkproductException::TBKPRODUCT_IS_NOT_EXISTS, TbkproductException::TBKPRODUCT_IS_NOT_EXISTS_NO);
    }

    static public function getOrderList($parameters = []) {
        $url_arr['appkey'] = self::TKURL_APP;
        $url_arr['start_time'] = isset($parameters['start_time']) ? urldecode($parameters['start_time']) : urldecode(date("Y-m-d H:i:00", time() - 60));
        $url_arr['end_time'] = isset($parameters['end_time']) ? urldecode($parameters['end_time']) : urldecode(date("Y-m-d H:i:00", time()));
        $url_arr['tk_status'] = isset($parameters['tk_status']) ? $parameters['tk_status'] : 12;
        if (isset($parameters['position_index']))
            $url_arr['position_index'] = $parameters['position_index'];
        $url_arr['session'] = self::SESSION;
        if (isset($parameters['query_type']))
            $url_arr['query_type'] = $parameters['query_type'];

        $url = self::TKURL_ORDER_LIST_URL . '?' . http_build_query($url_arr);

//        list($header_size, $resp) = RequestHelper::curlRequest($url);
        $resp = file_get_contents($url);
        $resp = json_decode($resp, true);

        $has_next = false;
        $order_arr = [];
        $position_index = '';
        if (isset($resp['tbk_sc_order_details_get_response']['data']) && !empty($resp['tbk_sc_order_details_get_response']['data'])) {

            if (! empty($resp['tbk_sc_order_details_get_response']['data']['results'])) {
                $position_index = $resp['tbk_sc_order_details_get_response']['data']['position_index'];
                $has_next = $resp['tbk_sc_order_details_get_response']['data']['has_next'];
                foreach ($resp['tbk_sc_order_details_get_response']['data']['results']['publisher_order_dto'] as $order_info) {
                    array_push($order_arr, [
                        'click_time' => $order_info['click_time'],
                        'create_time' => $order_info['tk_create_time'],
                        'pay_time' => $order_info['tb_paid_time'],
                        'settlement_time' => $order_info['tb_paid_time'],
                        'tb_pay_time' => $order_info['tb_paid_time'],
                        'item_id' => $order_info['item_id'],
                        'title' => $order_info['item_title'],
                        'image' => $order_info['item_img'],
                        'shop_title' => $order_info['seller_shop_title'],
                        'aliwangwang' => $order_info['seller_nick'],
                        'total' => $order_info['item_num'],
                        'price' => $order_info['item_price'],
                        'category' => $order_info['item_category_name'],
                        'order_sn' => $order_info['trade_id'],
                        'sub_order_sn' => $order_info['trade_parent_id'],
                        'order_stats' => $order_info['tk_status'] == 12 ? 2 :
                            ($order_info['tk_status'] == 13 ? 1 :
                                ($order_info['tk_status'] == 14 ? 3 :
                                    ($order_info['tk_status'] == 3 ? 4 : 0))),
                        'payment_amount' => $order_info['alipay_total_price'],
                        'settlement_amount' => $order_info['alipay_total_price'],
                        'commission_ratio' => $order_info['total_commission_rate'],
                        'commission' => $order_info['total_commission_fee'],
                        'subsidy_ratio' => $order_info['subsidy_rate'],
                        'type' => $order_info['order_type'],
                        'subsidy_amount' => $order_info['subsidy_fee'],
                        'subsidy_type' => 0.00,
                        'income_ratio' => $order_info['tk_total_rate'],
                        'split_ratio' => 0.00,
                        'income' => $order_info['total_commission_fee'],
                        'tech_service_rate' => $order_info['tk_commission_rate_for_media_platform'],
                        'tech_service_fee' => $order_info['tk_commission_pre_fee_for_media_platform'],
                        'effect_estimates' => $order_info['pub_share_pre_fee'],
                        'estimated_income' => $order_info['pub_share_fee'],
                        'source_id' => $order_info['site_id'],
                        'ad_id' => $order_info['adzone_id'],
                        'ad_name' => $order_info['adzone_name'],
                        'source_name' => $order_info['site_name'],
                        'transaction_platform' => $order_info['terminal_type'],
                    ]);
                }
            }

        }

        return [$position_index, $order_arr, $has_next];
    }

    static public function tpwdConvert($content = '') {

        $url_arr['appkey'] = self::TKURL_APP;
        $url_arr['content'] = $content;

        $url = self::TKURL_TPWD_CONVERT_URL . '?' . http_build_query($url_arr);

        list($header_size, $resp) = RequestHelper::curlRequest($url);
        $resp = json_decode($resp, true);

        $num_id = '';
        if (isset($resp['num_iid']) && !empty($resp['num_iid']))
            $num_id = $resp['num_iid'];

        return $num_id;
    }
}
